<script setup lang="ts">
import { ref, onMounted, reactive, onBeforeUnmount } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import Map from '@arcgis/core/Map'
import MapView from '@arcgis/core/views/MapView'
import WebTileLayer from '@arcgis/core/layers/WebTileLayer'
import DistanceMeasurement2D from '@arcgis/core/widgets/DistanceMeasurement2D'
import AreaMeasurement2D from '@arcgis/core/widgets/AreaMeasurement2D'
import gaodeLayer from '@/utils/GaoDeBaseLayer'
import {
  initLandslideLayer,
  getLandslideFeatures,
  addLandslideFeature,
  updateLandslideFeature,
  deleteLandslideFeature,
  getLandslideSymbol,
} from '@/services/landslideService'
import type { FormInstance, FormRules } from 'element-plus'

const formRef = ref<FormInstance>()
const loading = ref(false)
const mapContainer = ref<HTMLDivElement>()
const rules: FormRules = {
  name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
  Address: [{ required: true, message: '请输入地址', trigger: 'blur' }],
  occuredTime: [{ required: true, message: '请输入发生时间', trigger: 'blur' }],
  riskLevel: [{ required: true, message: '请选择风险等级', trigger: 'change' }],
  longitude: [
    { required: true, message: '请输入经度', trigger: 'blur' },
    { pattern: /^-?\d+(\.\d+)?$/, message: '经度格式错误', trigger: 'blur' },
  ],
  latitude: [
    { required: true, message: '请输入纬度', trigger: 'blur' },
    { pattern: /^-?\d+(\.\d+)?$/, message: '纬度格式错误', trigger: 'blur' },
  ],
}

// ArcGIS 相关实例用普通变量
let mapView: any = null
let landslideLayer: any = null
let distanceMeasurement: any = null
let areaMeasurement: any = null

// 图层控制
const baseLayerType = ref('gaode')
const layerVisibility = reactive({
  landslide: true,
})
const symbolType = ref('default')

// 工具相关
const measureType = ref('none')

/**
 * 初始化地图
 */
async function initMap() {
  const map = new Map({
    basemap: {
      baseLayers: [gaodeLayer],
    },
  })
  landslideLayer = initLandslideLayer()
  map.add(landslideLayer)

  mapView = new MapView({
    map,
    center: [106.753, 31.857],
    zoom: 10,
  })
}

onMounted(async () => {
  // 初始化地图
  await initMap()
  await loadFeatures()

  // 确保地图容器已经挂载
  if (mapContainer.value) {
    mapView.container = mapContainer.value

    // 添加地图点击事件
    mapView.on('click', (event: any) => {
      // 只有当 mapClickEnabled 为 true 时才响应点击事件
      console.log('地图点击事件触发:', event, '当前地图点击状态:', mapClickEnabled.value)

      if (mapClickEnabled.value) {
        const { longitude, latitude } = event.mapPoint
        console.log('符合条件，设置经纬度:', longitude, latitude)
        tempLngLat.value = {
          longitude: longitude.toFixed(6),
          latitude: latitude.toFixed(6),
        }
        mapPointConfirmDialogVisible.value = true

        // 获取经纬度后，禁用地图点击功能，避免再次触发
        mapClickEnabled.value = false
      } else {
        console.log('不符合条件，点击被忽略', {
          mapClickEnabled: mapClickEnabled.value,
          addMethod: addMethod.value,
          isEdit: isEdit.value,
          addMethodDialogVisible: addMethodDialogVisible.value,
          dialogVisible: dialogVisible.value,
          mapPointConfirmDialogVisible: mapPointConfirmDialogVisible.value,
        })
      }
    })
  }

  // 添加进入动画类
  setTimeout(() => {
    pageClass.value = 'page-show'
  }, 100)
})

/**
 * 切换测量工具
 */
function toggleMeasureTool() {
  if (!mapView) return

  // 移除现有的测量部件
  if (distanceMeasurement) {
    distanceMeasurement.visible = false
  }

  if (areaMeasurement) {
    areaMeasurement.visible = false
  }

  if (measureType.value === 'none') {
    ElMessage.info('已关闭测量工具')
    return
  }

  if (measureType.value === 'distance') {
    // 如果距离测量部件不存在，创建一个新的
    if (!distanceMeasurement) {
      distanceMeasurement = new DistanceMeasurement2D({
        view: mapView,
        unit: 'kilometers',
      })
      mapView.ui.add(distanceMeasurement, 'bottom-right')
    }

    // 显示距离测量部件
    distanceMeasurement.visible = true

    // 开始新的测量
    distanceMeasurement.viewModel.newMeasurement()

    ElMessage.info('已启用距离测量工具，请在地图上点击开始测量')
  } else if (measureType.value === 'area') {
    // 如果面积测量部件不存在，创建一个新的
    if (!areaMeasurement) {
      areaMeasurement = new AreaMeasurement2D({
        view: mapView,
        unit: 'square-kilometers',
      })
      mapView.ui.add(areaMeasurement, 'bottom-right')
    }

    // 显示面积测量部件
    areaMeasurement.visible = true

    // 开始新的测量
    areaMeasurement.viewModel.newMeasurement()

    ElMessage.info('已启用面积测量工具，请在地图上点击开始测量')
  }
}

/**
 * 更改基础图层
 */
function changeBaseLayer() {
  if (!mapView) return

  // 移除当前基础图层
  if (mapView.map.basemap.baseLayers.length > 0) {
    mapView.map.basemap.baseLayers.removeAll()
  }

  // 添加新的基础图层
  if (baseLayerType.value === 'gaode') {
    // 高德地图
    mapView.map.basemap.baseLayers.add(gaodeLayer)
  } else if (baseLayerType.value === 'satellite') {
    // 卫星影像（这里使用高德卫星图层，实际应用中可以替换为真实的卫星图层）
    const satelliteLayer = new WebTileLayer({
      urlTemplate: 'https://webst02.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}',
      copyright: '高德卫星影像',
    })
    mapView.map.basemap.baseLayers.add(satelliteLayer)
  }
}

/**
 * 切换图层可见性
 * @param layerName 图层名称
 */
function toggleLayerVisibility(layerName: string) {
  if (layerName === 'landslide' && landslideLayer) {
    landslideLayer.visible = layerVisibility.landslide
  }
}

/**
 * 更改符号类型
 */
function changeSymbolType() {
  if (!landslideLayer) return

  if (symbolType.value === 'risk') {
    // 根据风险等级设置不同的符号
    const renderer = {
      type: 'unique-value',
      field: 'riskLevel',
      defaultSymbol: {
        type: 'simple-marker',
        color: [128, 128, 128], // 灰色
        size: 8,
        outline: {
          color: [255, 255, 255],
          width: 1,
        },
      },
      uniqueValueInfos: [
        {
          value: '低风险',
          symbol: {
            type: 'simple-marker',
            color: [76, 175, 80], // 绿色
            size: 8,
            outline: {
              color: [255, 255, 255],
              width: 1,
            },
          },
        },
        {
          value: '中风险',
          symbol: {
            type: 'simple-marker',
            color: [255, 235, 59], // 黄色
            size: 10,
            outline: {
              color: [255, 255, 255],
              width: 1,
            },
          },
        },
        {
          value: '高风险',
          symbol: {
            type: 'simple-marker',
            color: [255, 152, 0], // 橙色
            size: 12,
            outline: {
              color: [255, 255, 255],
              width: 1,
            },
          },
        },
        {
          value: '极高风险',
          symbol: {
            type: 'simple-marker',
            color: [244, 67, 54], // 红色
            size: 14,
            outline: {
              color: [255, 255, 255],
              width: 1,
            },
          },
        },
      ],
    }

    landslideLayer.renderer = renderer
  } else {
    // 使用默认符号
    landslideLayer.renderer = {
      type: 'simple',
      symbol: {
        type: 'simple-marker',
        color: [226, 119, 40],
        size: 12,
        outline: {
          color: [255, 255, 255],
          width: 2,
        },
      },
    }
  }
}

onBeforeUnmount(() => {
  if (distanceMeasurement) {
    distanceMeasurement = null
  }

  if (areaMeasurement) {
    areaMeasurement = null
  }

  if (mapView) {
    mapView = null
  }
})

/**
 * 将 ArcGIS Feature 对象转换为普通 JavaScript 对象
 * 避免将复杂的 ArcGIS 对象放入 Vue 的响应式系统
 */
function convertFeatureToPlainObject(feature: any) {
  if (!feature) return null

  return {
    id: feature.attributes.OBJECTID,
    attributes: {
      name: feature.attributes.name || '',
      Address: feature.attributes.Address || '',
      occuredTime: feature.attributes.occuredTime || '',
      Description: feature.attributes.Description || '',
      riskLevel: feature.attributes.riskLevel || '低风险',
    },
    geometry: {
      longitude: feature.geometry ? feature.geometry.longitude : null,
      latitude: feature.geometry ? feature.geometry.latitude : null,
    },
  }
}

/**
 * 加载滑坡要素列表
 */
async function loadFeatures() {
  try {
    // 使用普通变量存储 ArcGIS Feature 对象
    rawFeatures = await getLandslideFeatures()

    // 将 ArcGIS Feature 对象转换为普通 JavaScript 对象，然后存储在 ref 中
    features.value = rawFeatures.map((feature: any) => convertFeatureToPlainObject(feature))

    console.log('加载滑坡要素成功，共', features.value.length, '条')
  } catch (e) {
    console.error('加载滑坡要素失败:', e)
    ElMessage.error('滑坡要素加载失败')
    rawFeatures = []
    features.value = []
  }
}

// 动画效果相关
const pageClass = ref('')

// 滑坡要素数据 - 使用普通变量存储 ArcGIS 对象，避免 Vue 响应式系统的问题
// 使用普通数组存储原始 ArcGIS Feature 对象
let rawFeatures: any = []
// 使用 ref 存储处理后的数据（不包含复杂的 ArcGIS 对象）
const features = ref([])
// 使用普通变量存储选中的 Feature
let rawSelectedFeature: any = null
// 使用 ref 存储选中 Feature 的 ID
const selectedFeatureId = ref(null)
// 控制地图点击是否可以添加要素
const mapClickEnabled = ref(false)
const dialogVisible = ref(false)
const addMethodDialogVisible = ref(false)
const addMethod = ref<'map' | 'manual' | null>(null)
const isEdit = ref(false)
const form = reactive({
  name: '',
  Address: '',
  occuredTime: '',
  Description: '',
  riskLevel: '低风险',
  longitude: '',
  latitude: '',
})

// 风险等级选项
const riskLevelOptions = [
  { value: '低风险', label: '低风险' },
  { value: '中风险', label: '中风险' },
  { value: '高风险', label: '高风险' },
  { value: '极高风险', label: '极高风险' },
]

/**
 * 根据风险等级获取对应的标签类型
 * @param riskLevel 风险等级
 * @returns 标签类型
 */
function getRiskLevelType(riskLevel: string): '' | 'success' | 'warning' | 'danger' {
  switch (riskLevel) {
    case '低风险':
      return 'success'
    case '中风险':
      return 'warning'
    case '高风险':
      return 'danger'
    case '极高风险':
      return 'danger'
    default:
      return ''
  }
}

function openAddDialog() {
  addMethod.value = null
  addMethodDialogVisible.value = true
}

/**
 * 处理选择经纬度获取方式
 * @param method 获取方式：'map' 地图点击，'manual' 手动输入
 */
function handleSelectAddMethod(method: 'map' | 'manual') {
  addMethod.value = method
  addMethodDialogVisible.value = false
  isEdit.value = false
  Object.assign(form, {
    name: '',
    Address: '',
    occuredTime: '',
    Description: '',
    riskLevel: '低风险',
    longitude: '',
    latitude: '',
  })

  if (method === 'manual') {
    // 手动输入方式，直接打开表单
    mapClickEnabled.value = false // 禁用地图点击
    dialogVisible.value = true
  } else if (method === 'map') {
    // 地图点击方式，启用地图点击功能
    mapClickEnabled.value = true

    // 提示用户点击地图
    ElMessage({
      message: '请点击地图上的位置来获取经纬度',
      type: 'info',
      duration: 3000,
    })

    console.log('已启用地图点击功能，当前状态:', mapClickEnabled.value)
  }
}

/**
 * 打开编辑对话框
 * @param feature 要编辑的滑坡要素（已转换为普通对象）
 */
function openEditDialog(feature: any) {
  isEdit.value = true

  // 填充表单数据
  Object.assign(form, {
    name: feature.attributes.name,
    Address: feature.attributes.Address,
    occuredTime: feature.attributes.occuredTime,
    Description: feature.attributes.Description,
    riskLevel: feature.attributes.riskLevel || '低风险',
    longitude: feature.geometry?.longitude || '',
    latitude: feature.geometry?.latitude || '',
  })

  // 查找原始 ArcGIS Feature 对象
  const featureId = feature.id
  rawSelectedFeature = rawFeatures.find((f: any) => f.attributes.OBJECTID === featureId)
  selectedFeatureId.value = featureId

  dialogVisible.value = true
}

function handleDialogClose() {
  dialogVisible.value = false
}

/**
 * 保存滑坡要素
 */
async function handleSave() {
  if (!formRef.value) return
  await formRef.value.validate(async (valid: boolean) => {
    if (!valid) return
    loading.value = true
    try {
      if (isEdit.value && selectedFeatureId.value && rawSelectedFeature) {
        // 编辑现有要素
        await updateLandslideFeature(selectedFeatureId.value, {
          name: form.name,
          Address: form.Address,
          occuredTime: form.occuredTime,
          Description: form.Description,
          riskLevel: form.riskLevel,
        })
        ElMessage.success('编辑成功')
      } else {
        // 添加新要素
        await addLandslideFeature({
          geometry: {
            longitude: Number(form.longitude),
            latitude: Number(form.latitude),
          },
          attributes: {
            name: form.name,
            Address: form.Address,
            occuredTime: form.occuredTime,
            Description: form.Description,
            riskLevel: form.riskLevel,
          },
        })
        ElMessage.success('新增成功')
      }
      dialogVisible.value = false

      // 重新加载要素列表
      await loadFeatures()

      // 清除选中状态
      rawSelectedFeature = null
      selectedFeatureId.value = null

      // 禁用地图点击功能
      mapClickEnabled.value = false
      console.log('保存成功，已禁用地图点击功能')
    } catch (e) {
      console.error('保存滑坡要素失败:', e)
      ElMessage.error('操作失败')
    } finally {
      loading.value = false
    }
  })
}

/**
 * 确认删除滑坡要素
 * @param feature 要删除的滑坡要素（已转换为普通对象）
 */
function confirmDelete(feature: any) {
  ElMessageBox.confirm(`确定要删除滑坡要素 "${feature.attributes.name}" 吗？`, '删除确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      handleDelete(feature)
    })
    .catch(() => {
      // 用户取消删除
    })
}

/**
 * 删除滑坡要素
 * @param feature 要删除的滑坡要素（已转换为普通对象）
 */
async function handleDelete(feature: any) {
  try {
    // 使用 feature.id 而不是直接访问 ArcGIS 对象
    await deleteLandslideFeature(feature.id)
    ElMessage.success('删除成功')

    // 重新加载要素列表
    await loadFeatures()
  } catch (e) {
    console.error('删除滑坡要素失败:', e)
    ElMessage.error('删除失败')
  }
}

/**
 * 定位到滑坡要素
 * @param feature 要定位的滑坡要素（已转换为普通对象）
 */
function locateFeature(feature: any) {
  if (!mapView || !feature.geometry) return

  const { longitude, latitude } = feature.geometry

  // 移动到要素位置
  mapView.goTo(
    {
      center: [longitude, latitude],
      zoom: 15,
    },
    {
      duration: 1000,
    },
  )

  ElMessage.success(`已定位到 "${feature.attributes.name}"`)
}

/**
 * 处理表格行点击事件
 * @param row 点击的行数据
 */
function handleRowClick(row: any) {
  locateFeature(row)
}

/**
 * 获取高风险滑坡数量
 * @returns 高风险滑坡数量
 */
function getHighRiskCount() {
  return features.value.filter(
    (feature: any) =>
      feature.attributes.riskLevel === '高风险' || feature.attributes.riskLevel === '极高风险',
  ).length
}

const mapPointConfirmDialogVisible = ref(false)
const tempLngLat = ref<{ longitude: string; latitude: string } | null>(null)

/**
 * 获取当前格式化的日期时间（使用2025年）
 * @returns 格式化的日期时间字符串，格式：YYYY-MM-DD HH:mm:ss
 */
function getCurrentDateTime() {
  const now = new Date()
  const year = 2025 // 固定使用2025年
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  const hours = String(now.getHours()).padStart(2, '0')
  const minutes = String(now.getMinutes()).padStart(2, '0')
  const seconds = String(now.getSeconds()).padStart(2, '0')

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

/**
 * 确认地图点击选择的经纬度
 */
function handleMapPointConfirm() {
  if (tempLngLat.value) {
    form.longitude = tempLngLat.value.longitude
    form.latitude = tempLngLat.value.latitude

    // 自动填入当前时间
    form.occuredTime = getCurrentDateTime()
  }

  // 关闭确认对话框，打开表单对话框
  mapPointConfirmDialogVisible.value = false
  dialogVisible.value = true

  // 禁用地图点击功能，避免再次触发
  mapClickEnabled.value = false
  console.log('已确认经纬度，禁用地图点击功能')
}

/**
 * 取消地图点击选择的经纬度
 */
function handleMapPointCancel() {
  mapPointConfirmDialogVisible.value = false
  tempLngLat.value = null

  // 禁用地图点击功能
  mapClickEnabled.value = false
  console.log('已禁用地图点击功能')
}
</script>

<template>
  <div class="landslide-management" :class="pageClass">
    <div class="page-header">
      <h1>滑坡要素管理</h1>
      <div class="header-actions">
        <el-button type="primary" size="small" @click="openAddDialog">
          <el-icon><Plus /></el-icon> 新增滑坡要素
        </el-button>
      </div>
    </div>

    <div class="page-layout">
      <!-- 控制面板 -->
      <div class="control-panel">
        <el-tabs type="border-card">
          <!-- 数据管理标签页 -->
          <el-tab-pane label="数据管理">
            <div class="tab-content">
              <el-table
                :data="features"
                style="width: 100%"
                height="calc(100vh - 280px)"
                :highlight-current-row="true"
                @row-click="handleRowClick"
              >
                <el-table-column prop="attributes.name" label="名称" min-width="100" />
                <el-table-column
                  prop="attributes.Address"
                  label="地址"
                  min-width="120"
                  show-overflow-tooltip
                />
                <el-table-column prop="attributes.occuredTime" label="发生时间" min-width="150" />
                <el-table-column prop="attributes.riskLevel" label="风险等级" width="100">
                  <template #default="scope">
                    <el-tag :type="getRiskLevelType(scope.row.attributes.riskLevel)">
                      {{ scope.row.attributes.riskLevel }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="120" fixed="right">
                  <template #default="scope">
                    <el-dropdown trigger="click">
                      <el-button size="small" type="primary" plain>
                        操作<el-icon class="el-icon--right"><ArrowDown /></el-icon>
                      </el-button>
                      <template #dropdown>
                        <el-dropdown-menu>
                          <el-dropdown-item @click.stop="openEditDialog(scope.row)">
                            <el-icon><Edit /></el-icon> 编辑
                          </el-dropdown-item>
                          <el-dropdown-item @click.stop="locateFeature(scope.row)">
                            <el-icon><Location /></el-icon> 定位
                          </el-dropdown-item>
                          <el-dropdown-item
                            divided
                            @click.stop="confirmDelete(scope.row)"
                            style="color: #f56c6c"
                          >
                            <el-icon><Delete /></el-icon> 删除
                          </el-dropdown-item>
                        </el-dropdown-menu>
                      </template>
                    </el-dropdown>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-tab-pane>

          <!-- 图层控制标签页 -->
          <el-tab-pane label="图层控制">
            <div class="tab-content">
              <el-form label-position="top">
                <!-- 图层控制 -->
                <el-form-item label="基础图层">
                  <el-radio-group v-model="baseLayerType" @change="changeBaseLayer">
                    <el-radio-button label="gaode">高德地图</el-radio-button>
                    <el-radio-button label="satellite">卫星影像</el-radio-button>
                  </el-radio-group>
                </el-form-item>

                <!-- 滑坡要素图层控制 -->
                <el-form-item label="滑坡要素图层">
                  <el-switch
                    v-model="layerVisibility.landslide"
                    active-text="显示"
                    inactive-text="隐藏"
                    @change="toggleLayerVisibility('landslide')"
                  />
                </el-form-item>

                <!-- 风险等级样式 -->
                <el-form-item label="风险等级样式">
                  <el-radio-group v-model="symbolType" @change="changeSymbolType">
                    <el-radio label="default">默认样式</el-radio>
                    <el-radio label="risk">风险等级</el-radio>
                  </el-radio-group>
                </el-form-item>

                <!-- 图例 -->
                <el-form-item label="图例">
                  <div class="legend-container">
                    <div class="legend-item">
                      <div class="legend-symbol" style="background-color: #4caf50"></div>
                      <div class="legend-label">低风险</div>
                    </div>
                    <div class="legend-item">
                      <div class="legend-symbol" style="background-color: #ffeb3b"></div>
                      <div class="legend-label">中风险</div>
                    </div>
                    <div class="legend-item">
                      <div class="legend-symbol" style="background-color: #ff9800"></div>
                      <div class="legend-label">高风险</div>
                    </div>
                    <div class="legend-item">
                      <div class="legend-symbol" style="background-color: #f44336"></div>
                      <div class="legend-label">极高风险</div>
                    </div>
                  </div>
                </el-form-item>
              </el-form>
            </div>
          </el-tab-pane>

          <!-- 工具标签页 -->
          <el-tab-pane label="工具">
            <div class="tab-content">
              <el-form label-position="top">
                <!-- 测量工具 -->
                <el-form-item label="测量工具">
                  <el-radio-group v-model="measureType" @change="toggleMeasureTool">
                    <el-radio-button label="none">关闭</el-radio-button>
                    <el-radio-button label="distance">距离</el-radio-button>
                    <el-radio-button label="area">面积</el-radio-button>
                  </el-radio-group>
                </el-form-item>

                <!-- 数据统计 -->
                <el-form-item label="数据统计">
                  <el-card shadow="never" class="stat-card">
                    <div class="stat-item">
                      <div class="stat-label">总滑坡数量</div>
                      <div class="stat-value">{{ features.length }}</div>
                    </div>
                    <div class="stat-item">
                      <div class="stat-label">高风险滑坡</div>
                      <div class="stat-value">{{ getHighRiskCount() }}</div>
                    </div>
                  </el-card>
                </el-form-item>
              </el-form>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>

      <!-- 地图容器 -->
      <div class="map-container">
        <div ref="mapContainer" class="map-view-container"></div>
      </div>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑滑坡要素' : '新增滑坡要素'"
      @close="handleDialogClose"
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="80px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="地址" prop="Address">
          <el-input v-model="form.Address" />
        </el-form-item>
        <el-form-item label="发生时间" prop="occuredTime">
          <el-input v-model="form.occuredTime" />
        </el-form-item>
        <el-form-item label="详情">
          <el-input v-model="form.Description" type="textarea" />
        </el-form-item>
        <el-form-item label="风险等级" prop="riskLevel">
          <el-select v-model="form.riskLevel" placeholder="请选择风险等级" style="width: 100%">
            <el-option
              v-for="item in riskLevelOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="经度" prop="longitude">
          <el-input v-model="form.longitude" />
        </el-form-item>
        <el-form-item label="纬度" prop="latitude">
          <el-input v-model="form.latitude" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="handleDialogClose">取消</el-button>
        <el-button type="primary" :loading="loading" @click="handleSave">保存</el-button>
      </template>
    </el-dialog>

    <!-- 选择经纬度方式对话框 -->
    <el-dialog
      v-model="addMethodDialogVisible"
      title="请选择经纬度获取方式"
      width="340px"
      :close-on-click-modal="false"
      :show-close="false"
    >
      <div style="text-align: center">
        <el-button
          type="primary"
          @click="handleSelectAddMethod('map')"
          style="margin-bottom: 16px; width: 220px"
          >地图点击获取经纬度</el-button
        >
        <br />
        <el-button type="success" @click="handleSelectAddMethod('manual')" style="width: 220px"
          >手动输入经纬度</el-button
        >
      </div>
    </el-dialog>

    <!-- 地图点击获取经纬度确认对话框 -->
    <el-dialog v-model="mapPointConfirmDialogVisible" title="确认经纬度" width="400px">
      <div>经度：{{ tempLngLat?.longitude }}<br />纬度：{{ tempLngLat?.latitude }}</div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleMapPointCancel">取消</el-button>
          <el-button type="primary" @click="handleMapPointConfirm">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.landslide-management {
  background: linear-gradient(135deg, #ffecb3 0%, #ffcc80 100%);
  opacity: 0;
  transform: translateY(20px);
  transition: all 0.5s ease;
  height: 100%;
  padding: 16px;

  &.page-show {
    opacity: 1;
    transform: translateY(0);
  }
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;

  h1 {
    color: #b71c1c;
    margin: 0;
    text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.1);
  }

  .header-actions {
    display: flex;
    gap: 8px;
  }
}

.page-layout {
  display: flex;
  height: calc(100vh - 120px);
  gap: 16px;

  .control-panel {
    width: 400px;

    .el-tabs {
      height: 100%;
      border-color: #e65100;

      :deep(.el-tabs__header) {
        background: linear-gradient(to right, #ffb74d, #ff9800);
      }

      :deep(.el-tabs__item) {
        color: #7f4f24;

        &.is-active {
          color: #b71c1c;
          font-weight: bold;
        }

        &:hover {
          color: #e65100;
        }
      }

      :deep(.el-tabs__content) {
        height: calc(100% - 55px);
        overflow-y: auto;
        background-color: rgba(255, 248, 225, 0.9);
      }

      .tab-content {
        height: 100%;
        padding: 10px 0;
      }
    }

    :deep(.el-table) {
      background-color: transparent;

      .el-table__header th {
        background-color: #ffb74d;
        color: #7f4f24;
        font-weight: bold;
      }

      .el-table__row {
        background-color: rgba(255, 255, 255, 0.7);

        &:hover > td {
          background-color: rgba(255, 224, 178, 0.7) !important;
        }

        &.current-row > td {
          background-color: rgba(255, 204, 128, 0.7) !important;
        }
      }

      .el-table__row:nth-child(even) {
        background-color: rgba(255, 243, 224, 0.7);
      }
    }

    :deep(.el-button--primary) {
      background-color: #e65100;
      border-color: #e65100;

      &:hover,
      &:focus {
        background-color: #f57c00;
        border-color: #f57c00;
      }

      &.is-plain {
        color: #e65100;
        background-color: #fff3e0;
        border-color: #ffcc80;

        &:hover,
        &:focus {
          background-color: #ffe0b2;
          border-color: #e65100;
        }
      }
    }

    :deep(.el-button--danger) {
      background-color: #c62828;
      border-color: #c62828;

      &:hover,
      &:focus {
        background-color: #d32f2f;
        border-color: #d32f2f;
      }
    }

    :deep(.el-button--success) {
      background-color: #2e7d32;
      border-color: #2e7d32;

      &:hover,
      &:focus {
        background-color: #388e3c;
        border-color: #388e3c;
      }
    }

    :deep(.el-radio-button__inner) {
      background-color: #fff3e0;
      border-color: #ffcc80;
      color: #e65100;

      &:hover {
        color: #b71c1c;
      }
    }

    :deep(.el-radio-button__original-radio:checked + .el-radio-button__inner) {
      background-color: #e65100;
      border-color: #e65100;
      box-shadow: -1px 0 0 0 #e65100;
    }
  }

  .map-container {
    flex: 1;
    background: linear-gradient(135deg, #fff3e0 0%, #ffe0b2 100%);
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    overflow: hidden;
    border: 1px solid #ffcc80;

    .map-view-container {
      width: 100%;
      height: 100%;
    }
  }
}

.legend-container {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.legend-item {
  display: flex;
  align-items: center;
  margin-right: 15px;
}

.legend-symbol {
  width: 16px;
  height: 16px;
  border-radius: 50%;
  margin-right: 5px;
}

.legend-label {
  font-size: 12px;
  color: #7f4f24;
}

.stat-card {
  background: rgba(255, 248, 225, 0.7);
  border-color: #ffcc80;

  .stat-item {
    display: flex;
    justify-content: space-between;
    margin-bottom: 8px;

    .stat-label {
      font-weight: bold;
      color: #7f4f24;
    }

    .stat-value {
      font-size: 18px;
      color: #b71c1c;
      font-weight: bold;
    }
  }
}

:deep(.el-dialog) {
  background: linear-gradient(135deg, #fff8e1 0%, #fff3e0 100%);
  border: 1px solid #ffcc80;
  border-radius: 8px;

  .el-dialog__header {
    background: linear-gradient(to right, #ffb74d, #ff9800);
    color: #7f4f24;
    border-radius: 8px 8px 0 0;
    padding: 15px 20px;

    .el-dialog__title {
      color: #7f4f24;
      font-weight: bold;
    }
  }

  .el-dialog__body {
    color: #5d4037;
  }

  .el-form-item__label {
    color: #7f4f24;
  }

  .el-input__inner,
  .el-textarea__inner {
    border-color: #ffcc80;

    &:focus {
      border-color: #e65100;
    }
  }

  .el-select .el-input.is-focus .el-input__inner {
    border-color: #e65100;
  }
}

:deep(.el-dropdown-menu) {
  background-color: #fff8e1;
  border: 1px solid #ffcc80;

  .el-dropdown-menu__item {
    color: #7f4f24;

    &:hover {
      background-color: #ffe0b2;
      color: #e65100;
    }

    .el-icon {
      margin-right: 5px;
      color: #e65100;
    }
  }
}
</style>
